// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const { location } = event
  if (!location || !location.longitude || !location.latitude) {
    throw new Error('invalid location')
  }

  const { list } = await db
    .collection('screen')
    .aggregate()
    .geoNear({
      near: new db.Geo.Point(location.longitude, location.latitude),
      spherical: true,
      distanceField: 'distance',
      maxDistance: 100000,
    })
    .lookup({
      from: 'screen-cast',
      localField: '_id',
      foreignField: 'screen._id',
      as: 'casts',
    })
    .project({ 'casts._id': false, 'casts.screen': false })
    .end()

  return list
}
